using System.Diagnostics;
using MES_workbench.ErrorCode;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MES_workbench.Api.Filters
{
    /// <summary>
    /// 全局异常过滤器：拦截未处理异常并返回统一的 ApiResult 响应
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;
        private readonly IWebHostEnvironment _env;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }

        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            var traceId = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;
            var path = context.HttpContext.Request.Path.Value;

            // 记录错误日志
            _logger.LogError(ex, "[GlobalException] Unhandled exception. TraceId={TraceId}, Path={Path}", traceId, path);

            // 统一响应
            var api = new ApiResult
            {
                code = ApiREunm.Abnormal,
                msg = "服务器异常",
                data = new
                {
                    traceId,
                    path,
                    // 仅在开发环境返回详细错误，生产环境隐藏细节
                    error = _env.IsDevelopment() ? ex.Message : null
                }
            };

            context.Result = new ObjectResult(api)
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };
            context.ExceptionHandled = true;
        }
    }
}
